/* Laboratorio # 2 - Administración de bases de datos
 Jorge Fallas Ramos         402090469
 José Roberto Sánchez       115400070
 Daniel Villalobos Venegas  402110100
 */
package monitorinitdb.Vista;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import javax.swing.*;
import javax.swing.JPanel;
import javax.swing.filechooser.FileNameExtensionFilter;

public class VentanaArchiveLog extends JFrame implements ActionListener {

    JPanel panelArchv;
    ArrayList<JTextField> campoRuta;
    String[] acciones = {"Agregar Directorio", "Limpiar", "Continuar"};
    JButton seleccionaRuta, limpiar, continuar;
    int cantArchiv = 0;
    JFileChooser filechooser;
    public static VentanaArchiveLog instance;

    public static String getArchive() {
        if (instance != null) {
            return instance.obtDir();
        }
        return null;
    }

    public static VentanaArchiveLog getInstance() {
        if (instance == null) {
            instance = new VentanaArchiveLog();
        }
        return instance;
    }

    private VentanaArchiveLog() throws HeadlessException {
        campoRuta = new ArrayList<>();
        configuracionInicial();
        configChooser();
        ventanaInicial();
    }

    private void configuracionInicial() {
        setTitle("Archivos del Modo ARCHIVELOG");
        setPreferredSize(new Dimension(650, 420));
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        setResizable(false);

        addWindowListener(new WindowAdapter() {

            @Override
            public void windowClosing(WindowEvent e) {
                setVisible(false);
                VentConfig.getInstance().mostrar();
            }

        });
    }

    private void ventanaInicial() {
        JPanel panelPrincipal = new JPanel();
        panelPrincipal.setLayout(new BoxLayout(panelPrincipal, BoxLayout.Y_AXIS));
        panelArchv = new JPanel();
        panelArchv.setLayout(new BoxLayout(panelArchv, BoxLayout.Y_AXIS));

        JScrollPane scroll = new JScrollPane(panelArchv, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        scroll.setPreferredSize(new Dimension(550, 350));
        scroll.setMaximumSize(scroll.getPreferredSize());
        panelPrincipal.add(scroll, BorderLayout.CENTER);

        JPanel panelBotones = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        JButton b;
        for (String s : acciones) {
            b = new JButton(s);
            b.setActionCommand(s);
            b.addActionListener(this);
            panelBotones.add(b);
        }
        panelPrincipal.add(panelBotones, BorderLayout.SOUTH);
        this.add(panelPrincipal, BorderLayout.CENTER);
        JLabel lb = new JLabel("Carpeta(s) donde se guardaran los archive log");
        lb.setHorizontalAlignment(JLabel.CENTER);
        this.add(lb, BorderLayout.NORTH);
    }

    public void mostrar() {
        pack();
        setLocationRelativeTo(null);
        getContentPane().revalidate();
        setVisible(true);
    }

    private void configChooser() {
        filechooser = new JFileChooser();
        filechooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        filechooser.setFileFilter(new FileNameExtensionFilter("Carpetas", "*"));
        filechooser.setDialogType(JFileChooser.OPEN_DIALOG);
    }

    private File obtArchivo() throws HeadlessException {
        int respuesta = filechooser.showOpenDialog(null);
        if (respuesta == JFileChooser.APPROVE_OPTION && filechooser.getSelectedFile().isDirectory()) {
            if (filechooser.getSelectedFile().isDirectory()) {
                return filechooser.getSelectedFile();
            }
            throw new HeadlessException("Archivo no permitido");
        }
        return null;
    }

    private JPanel genArchivDir(File f) {
        String name = "ArchiveDir_" + cantArchiv;
        cantArchiv++;
        JPanel l = new JPanel(new FlowLayout());
        l.add(new JLabel("ArchiveDir:"));
        JTextField t = new JTextField(f.getAbsolutePath());
        t.setPreferredSize(new Dimension(200, 35));
        t.setName(name);
        t.setEditable(false);
        l.add(t);
        campoRuta.add(t);
        JButton b = new JButton("Eliminar");
        l.add(b);
        b.addActionListener(this);
        b.setName(name);
        b = new JButton("Editar");
        l.add(b);
        b.addActionListener(this);
        b.setName(name);
        l.setBorder(BorderFactory.createRaisedSoftBevelBorder());
        l.setName(name);
        return l;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (e.getActionCommand()) {
            case "Agregar Directorio": {
                if (campoRuta.size() < 30) {
                    try {
                        File f = obtArchivo();
                        if (f != null) {
                            panelArchv.add(genArchivDir(f));
                            VentConfig.incrementArchiv();
                        }
                    } catch (HeadlessException ex) {
                        System.err.println(ex.toString());
                    }
                } else {
                    JOptionPane.showMessageDialog(null, "Error: limite de directorios para ArchiveLog", "Error", JOptionPane.WARNING_MESSAGE);
                }
                getContentPane().revalidate();
            }
            break;
            case "Limpiar": {
                limpiar();
                getContentPane().revalidate();
                panelArchv.repaint();
            }
            break;
            case "Continuar": {
                setVisible(false);
                VentConfig.getInstance().mostrar();
            }
            break;
            case "Eliminar": {
                JButton bt = (JButton) e.getSource();
                for (int i = 0; i < panelArchv.getComponentCount(); i++) {
                    if (panelArchv.getComponents()[i].getName().equals(bt.getName())) {
                        panelArchv.remove(i);
                        VentConfig.decrementArchiv();
                        break;
                    }
                }
                panelArchv.repaint();
                getContentPane().revalidate();
            }
            break;
            case "Editar": {
                JButton bt = (JButton) e.getSource();
                File f = obtArchivo();
                if (f != null) {
                    for (int i = 0; i < panelArchv.getComponentCount(); i++) {
                        if (panelArchv.getComponents()[i].getName().equals(bt.getName())) {
                            campoRuta.get(i).setText(f.getAbsolutePath());
                            break;
                        }
                    }
                }
                panelArchv.repaint();
                getContentPane().revalidate();
            }
            break;
            default:
                throw new UnsupportedOperationException("Not supported yet." + e.getActionCommand());
        }
    }

    public static void clean() {
        if (instance != null) {
            instance.limpiar();
        }
    }

    void limpiar() {
        campoRuta.clear();
        panelArchv.removeAll();
    }

    public static void main(String[] args) {
        VentanaArchiveLog.getInstance().mostrar();
    }

    public String obtDir() {
        StringBuilder hilera = new StringBuilder();
        String inst = "ALTER SYSTEM SET LOG_ARCHIVE_DEST_";
        for (int i = 0; i < campoRuta.size(); i++) {
            hilera.append(inst).append(i + 1).append(" = 'LOCATION=").append(campoRuta.get(i).getText()).append("';\n");
        }
        return hilera.toString();
    }
}
